﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using UnityEngine;

public class RoleSystem : ILogic
{
    private DataServiceBase dataService;
    private ResService resService;
    private RoleConfigSO roleConfigSO { get; set; }
    private AIConfigSO AIConfigSO { get; set; }

    public Dictionary<GameRole, RoleConfig> currentRoleDic;//玩家配置
    public List<GameRole> roleNameList;//当前玩法（场景）内的Role
    public GameRole firstRole;

    public List<List<GameObject>> progressIndexList ;
    private Action<int> progressCompleteCB = null;


    public GameObject RoleRoot;
    public GameObject AIRoot;
    
    public void OnInit()
    {
        #region 创建节点
        RoleRoot = GameObject.Find("RoleRoot");
        if (RoleRoot == null)
        {
            RoleRoot = new GameObject("RoleRoot");
            RoleRoot.transform.SetParent(GameRoot.Instance.transform);
        }
        else
        {
            for (int i = 0; i < RoleRoot.transform.childCount; i++)
            {
                GameObject.Destroy(RoleRoot.transform.GetChild(i));
            }
        }

        AIRoot = GameObject.Find("AIRoot");
        if (AIRoot == null)
        {
            AIRoot = new GameObject("AIRoot");
            AIRoot.transform.SetParent(GameRoot.Instance.transform);
        }
        else
        {
            for (int i = 0; i < AIRoot.transform.childCount; i++)
            {
                GameObject.Destroy(AIRoot.transform.GetChild(i));
            }
        }
        #endregion
        resService = GameRoot.Instance.resService;
        dataService = GameRoot.Instance.dataService;
        currentRoleDic = new Dictionary<GameRole, RoleConfig>();
        roleNameList = new List<GameRole>();
        progressIndexList =new List<List<GameObject>>();

        roleConfigSO = resService.LoadSO<RoleConfigSO>(GameResPathConfig.RoleConfig, false);
        AIConfigSO = resService.LoadSO<AIConfigSO>(GameResPathConfig.AIConfig, false);
    }
    public void OnUpdate()
    {

    }

    public void UnInit()
    {
        
    }
    public void OnExit()
    {
        for (int i = 0; i < roleNameList.Count; ++i)
        {
            currentRoleDic[roleNameList[i]].player.OnExit();
        }
    }
    //角色的实例化
    /// <summary>
    /// 由StageService层来调用
    /// </summary>
    public void LoadRole(StageRoleConfig stageRoleConfig, List<GameRole> roleNames = null)
    {
        if (stageRoleConfig == null)
        {
            this.Warn("stageRoleConfig is null! failed create roles");
            if (roleNameList.Count > 0)
            {
                foreach (var r in roleNameList)
                {
                    currentRoleDic[r].player.UnInit();
                    GameObject.Destroy(currentRoleDic[r].roleGO);
                }
                currentRoleDic.Clear();
                roleNameList.Clear();
            }
            return;
        }
        List<GameRole> targetRoleList = stageRoleConfig.RoleContainer.Count == 0 ? roleNames : stageRoleConfig.RoleContainer;
        if (targetRoleList == null)
        {
            this.Warn("targetRoleList is null! failed create roles");
            if (roleNameList.Count > 0)
            {
                foreach (var r in roleNameList)
                {
                    currentRoleDic[r].player.UnInit();
                    GameObject.Destroy(currentRoleDic[r].roleGO);
                }
                currentRoleDic.Clear();
                roleNameList.Clear();
            }
            return;
        }
        DeleteNotUseRole(targetRoleList);

        List<GameRole> oldRoleList = new List<GameRole>();
        List<GameRole> newRoleList = new List<GameRole>();
        //找到之前还存在的角色和新角色
        foreach (var role in targetRoleList)
        {
            if (currentRoleDic.ContainsKey(role))
            {
                oldRoleList.Add(role);
            }
            else
            {
                newRoleList.Add(role);
            }
        }
        //处理之前还存在的角色
        foreach (var role in oldRoleList)
        {
            //反初始化
            currentRoleDic[role].roleGO.SetActive(false);
        }
        //创建新角色
        for (int i = 0; i < newRoleList.Count; ++i)
        {
            if (newRoleList[i] == GameRole.Null)
            {
                continue;
            }
            InitRole(newRoleList[i]);
        }
        //处理当前场景的角色
        if (roleNameList.Count == 0) { this.Warn("Any role is not registered in stage"); return; }
        //默认将第一个角色Go激活
        firstRole = currentRoleDic[roleNameList[0]].RoleName;
        //设置位置
        ResetRolePosInfo(currentRoleDic[firstRole].roleGO.transform);
        currentRoleDic[firstRole].roleGO.SetActive(true);

        //初始化所有角色
        for (int i = 0; i < roleNameList.Count; ++i)
        {
            currentRoleDic[roleNameList[i]].player.OnEnter();
        }
    }

    private void DeleteNotUseRole(List<GameRole> targetRoleList)
    {
        List<GameRole> dontNeedRoleList = new List<GameRole>();
        // 找到不需要的角色
        foreach (var role in currentRoleDic.Keys.ToList()) // 使用 ToList() 避免修改集合时出错
        {
            if (!targetRoleList.Contains(role)) // 使用 Contains 替代 Find 检查
            {
                dontNeedRoleList.Add(role);
            }
        }
        // 处理不需要的角色
        foreach (var role in dontNeedRoleList)
        {
            if (currentRoleDic.TryGetValue(role, out var roleData))
            {
                roleData.player.UnInit();
                GameObject.Destroy(roleData.roleGO);
                currentRoleDic.Remove(role);
                roleNameList.Remove(role);
            }
        }
    }


    private void InitRole(GameRole targetRole)
    {
        var config = roleConfigSO.roleConfigs.Find(c => c.RoleName == targetRole);//从配置中获取目标Role
        if (config != null)
        {
            currentRoleDic[targetRole] = config;//添加到字典
            if (config.rolePrefab == null)
            {
                this.Error("RoleConfigSO中的Prefab为空");
                return;
            }
            var go = GameObject.Instantiate(config.rolePrefab, RoleRoot.transform);
            //TODO添加对象池，避免每次进入场景都需要实例
            go.SetActive(false);
            config.roleGO = go;
            if (config.lookAtPath != string.Empty)
            {
                config.lookAt = go.transform.Find(config.lookAtPath);
            }
            if (config.followAtPath != string.Empty)
            {
                config.followAt = go.transform.Find(config.followAtPath);
            }
            config.player = go.GetComponent<Player>();
            if (config.player == null)
            {
                config.player = go.AddComponent<Player>();
            }
            config.player.OnAwake();
            roleNameList.Add(targetRole);//添加RoleName列表
        }
    }

    private void ResetRolePosInfo(Transform role)
    {
        GameData gameData = dataService.GetOneGameData(dataService.currentGameDataID);
        if (gameData == null|| gameData.playerData == null)
        {
            var roleConfig = GameRoot.Instance.stageSystem.currentStageConfig.RoleConfig;
            Vector3 pos;
            Vector3 faceDir;
            if (roleConfig != null)
            {
                pos = roleConfig.pos;
                faceDir = roleConfig.EulerAngle;
            }
            else
            {
                pos = Vector3.zero;
                faceDir = Vector3.zero;
            }
            role.position = pos;
            role.eulerAngles = faceDir;
            return;
        }
        role.position = gameData.playerData.Pos.SerializeToUnity();
        role.eulerAngles = gameData.playerData.FaceDir.SerializeToUnity();
    }

    /// <summary>
    /// 由游戏模式层来调用
    /// </summary>
    /// <param name="stageAIContainerSO"></param>
    public void LoadAI(StageAIContainer stageAIContainer)
    {
        if (stageAIContainer == null)
        {
            this.Warn("stageAIContainerSO is null! failed create AI");
            return;
        }
        foreach (StageAIConfig stageAIConfigSO in stageAIContainer.stageAIConfigList)
        {
            if (stageAIConfigSO == null)
            {
                continue;
            }
            if (stageAIConfigSO.AIName== GameAI.Null)
            {
                continue;
            }
            GameObject prefab = AIConfigSO.GetAIPrefab(stageAIConfigSO.AIName);
            if (prefab != null)
            {
                GameObject go = GameObject.Instantiate(prefab, stageAIConfigSO.pos, Quaternion.Euler(stageAIConfigSO.eulerAngle), AIRoot.transform);
                go.SetActive(false);
                if (stageAIConfigSO.StageProgressIndex >= progressIndexList.Count)
                {
                    progressIndexList.Add(new List<GameObject>());//增加一次波次位
                }
                progressIndexList[stageAIConfigSO.StageProgressIndex].Add(go);//表示第几波次的敌人
            }
            else
            {
                this.Error($"Prefab for AI {stageAIConfigSO.AIName} not found!");
            }
        }
        if (progressIndexList.Count == 0) { this.Warn("Any AI is not registered in stage"); }
    }
    /// <summary>
    /// 激活AI（按波次来）
    /// </summary>
    /// <param name="progressIndex"></param>
    public void ActiveAI(int progressIndex)
    {
        if (progressIndex >= progressIndexList.Count)
        {
            this.Error($"progressIndex :{progressIndex} is out of range!");
            return;
        }
        foreach (var AI in progressIndexList[progressIndex])
        {
            AI.SetActive(true);
        }
    }
    /// <summary>
    /// 敌人手动调用
    /// </summary>
    /// <param name="progressIndex"></param>
    /// <param name="gameObject"></param>
    public void RemoveOneAI(int progressIndex, GameObject gameObject)
    {
        if (progressIndex >= progressIndexList.Count)
        {
            this.Error($"progressIndex :{progressIndex} is out of range!");
            return;
        }
        if (progressIndexList[progressIndex].Contains(gameObject))
        {
            progressIndexList[progressIndex].Remove(gameObject);
            if (progressIndexList[progressIndex].Count == 0)//波次打完触发Action
            {
                this.Log($"this {progressIndex} progress has completed！");
                progressCompleteCB?.Invoke(progressIndex);
            }
        }
        else
        {
            this.Error($"not exist this {gameObject} in progressIndexList in {progressIndex}(波次) !");
        }
    }
    public void AddProgressAction(Action<int> progressCompleteCB) => this.progressCompleteCB = progressCompleteCB;

    /// <summary>
    /// 得到第一个加载的角色数据
    /// </summary>
    /// <returns></returns>
    public RoleConfig GetDefaultRoleConfig()
    {
        return GetRoleConfig(firstRole);
    }

    /// <summary>
    /// 获取RoleConfig通过RoleName
    /// </summary>
    /// <param name="roleName"></param>
    /// <returns></returns>
    public RoleConfig GetRoleConfig(GameRole roleName)
    {
        if (currentRoleDic.TryGetValue(roleName, out var roleConfig))
        {
            return roleConfig;
        }
        else
        {
            this.Error($"{roleName} has no role name in currentRoleDic!!!");
            return null;
        }
    }

    public GameObject GetRole(int roleIndex)
    {
        if (roleIndex >= roleNameList.Count)
        {
            this.Error($"roleIndex:{roleIndex} is out of range in roleNameList ");
            return null;
        }
        return currentRoleDic[roleNameList[roleIndex]].roleGO;
    }

    public void OnEnterState()
    {
       
    }
}